<template>
  <!-- 自定义组件 -->
  <x-search>
    <!-- 搜索的一系列东西 -->
    <template #search>
      <a-input
        v-model:value="student_name"
        placeholder="请输入学生姓名"
        style="width: 150px"
      />
      <a-input
        v-model:value="title"
        placeholder="请输入作业名称(针对图)"
        style="width: 180px; margin-left: 10px"
      />
      <a-select
        v-model:value="program_id"
        placeholder="查询专业"
        style="width: 150px; margin-left: 10px"
        @change="proToclass"
      >
        <a-select-option
          v-for="(item, index) in all_programs"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>

      <a-select
        v-model:value="class_id"
        placeholder="查询班级"
        style="width: 150px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in all_classes"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>

      <a-range-picker
        style="margin-left: 10px"
        v-model:value="data_time_s"
        show-time
      />

      <a-button type="primary" style="margin-left: 10px" @click="but_search">
        <search-outlined style="margin-right: 5px" />
        查询</a-button
      >
      <a-button style="margin-left: 10px" @click="reset_search"
        ><redo-outlined style="margin-right: 5px" />重置</a-button
      >
    </template>
    <!-- 操作的一系列东西 -->
    <template #operate>
      <a-button
        type="primary"
        style="background: #52c41a; border-color: #52c41a"
      >
        <template #icon><export-outlined style="margin-right: 5px" /></template>
        导出</a-button
      >
    </template>
  </x-search>

  <!-- 统计图部分2个 -->
  <div class="chart">
    <!-- 学生作业提交趋势统计图 -->
    <x-card :message="message2" :width="49.5" :height="height1">
      <div ref="chartRef1" style="width: 100%; height: 300px"></div>
    </x-card>

    <!-- 作业难度热力分布图 -->
    <x-card :message="message1" :width="49.5" :height="height1">
      <div ref="chartRef2" style="width: 100%; height: 300px"></div>
    </x-card>
  </div>

  <!-- 表格区 -->
  <!-- 数据表格 -->
  <a-table
    :dataSource="tableData"
    :columns="columns"
    :loading="loading"
    :pagination="pagination"
    bordered
    style="margin-top: 10px"
    @change="handleTableChange"
    :scroll="{ x: 1300, y: 200 }"
  >
  </a-table>
</template>

<script setup lang="ts">
import BreadCrumb from "./BreadCrumb.vue";
import XCard from "./XCard.vue";
import XSearch from "./XSearch.vue";
import {
  ref,
  reactive,
  toRaw,
  onMounted,
  createVNode,
  watch,
  computed,
} from "vue";
import http from "../routerutils/http";
import { message, Modal, Cascader } from "ant-design-vue";
// 对话提示
import {
  SearchOutlined,
  FileTextOutlined,
  TeamOutlined,
  UserOutlined,
  ReadOutlined,
  BookOutlined,
  RedoOutlined,
  ExportOutlined,
} from "@ant-design/icons-vue";
// 表单验证
import type { Rule } from "ant-design-vue/es/form";
import type { UnwrapRef } from "vue";
import type { CascaderProps } from "ant-design-vue";
import { number } from "echarts";
import type { Dayjs } from "dayjs";
// 处理时间
import dayjs from "dayjs";
import * as echarts from "echarts";
import { TableProps } from "ant-design-vue";
type RangeValue = [Dayjs, Dayjs];
interface ClassInfo {
  id: string;
  name: string;
}
// 1. 搜索相关的操作数据
const student_name = ref<string>("");
const title = ref<string>("");
const class_id = ref();
const data_time_s = ref([]);
const program_id = ref();
const exam_data = ref<string>("");
const exam_type = ref();
// 重置按钮的方法
const reset_search = () => {
  student_name.value = "";
  class_id.value = null;
  program_id.value = null;
  exam_data.value = "";
  exam_type.value = null;
  data_time_s.value = [];
  title.value = "";
  fetchData();
  all_class();
  initChart1();
  initChart2();
};
// 搜索按钮的方法
const but_search = () => {
  fetchData();
  if (class_id.value || program_id.value || title.value || data_time_s.value) {
    initChart1();
  }
  if (class_id.value || program_id.value) {
    initChart2();
  }
};
// 后端接口所有班级数据
const all_classes = ref<ClassInfo[]>([]);
const all_class = async () => {
  try {
    const response = await http.get("/api/students/allclass");
    console.log(response.data.results);
    all_classes.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 后端接口所有专业数据
const all_programs = ref<ClassInfo[]>([]);
const all_program = async () => {
  try {
    const response = await http.get("/api/students/allprogram");
    console.log(response.data.results);
    all_programs.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};

// 根据专业id去获取对应的所以班级
const proToclass = async () => {
  try {
    const response = await http.get("/api/students/pro_class", {
      params: {
        program_id: program_id.value,
      },
    });
    console.log(response.data.results);
    all_classes.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};

onMounted(() => {
  all_class();
  all_program();
});

// 学生作业提交趋势表
const message2 = ref<string>("学生作业提交趋势表");
const height1 = ref<string>("400px");
const chartRef1 = ref<HTMLElement | null>(null);
const initChart1 = async () => {
  try {
    if (chartRef1.value !== null) {
      // title, class_id, program_id, start_time, end_time
      const response = await http.get("/api/assignments/sub_trend", {
        params: {
          title: title.value ? title.value.trim() : undefined,
          class_id: class_id.value,
          program_id: program_id.value,
          start_time: data_time_s.value[0]
            ? dayjs(data_time_s.value[0]).format("YYYY-MM-DD HH:mm:ss")
            : undefined,
          end_time: data_time_s.value[1]
            ? dayjs(data_time_s.value[1]).format("YYYY-MM-DD HH:mm:ss")
            : undefined,
        },
      });
      const work_list = response.data.results || [];

      // 1. 数据处理
      const statusTypes = [
        ...new Set(work_list.map((item: any) => item.status)),
      ]; // ['完成', '未完成', '迟交']
      const dates = [...new Set(work_list.map((item: any) => item.day))].sort(); // 排序日期
      console.log(statusTypes, dates);
      // 2. 创建系列数据
      const seriesData = statusTypes.map((status) => {
        return {
          name: status,
          type: "line",
          stack: "总量",
          areaStyle: {},
          emphasis: { focus: "series" },
          data: dates.map((date) => {
            // 找到日期对应的数量
            const item = work_list.find(
              (d: any) => d.day === date && d.status === status
            );
            return item ? item.count : 0;
          }),
        };
      });

      // 3. ECharts 配置
      const option = {
        title: {
          text: "作业提交趋势分析",
          left: "center",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "cross" },
        },
        legend: {
          data: statusTypes,
          top: 30,
        },
        toolbox: {
          feature: {
            saveAsImage: {
              title: "保存图片",
              pixelRatio: 2,
            },
          },
          right: 20,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            data: dates,
            axisLabel: {
              formatter: (value: string) => dayjs(value).format("MM-DD"), // 日期格式化
            },
          },
        ],
        yAxis: [{ type: "value" }],
        series: seriesData,
      };

      // 4. 渲染图表
      const myChart = echarts.init(chartRef1.value);
      myChart.setOption(option);

      // 窗口大小自适应
      window.addEventListener("resize", () => myChart.resize());
    }
  } catch (error) {
    console.error("图表初始化失败:", error);
  }
};

// 作业难度热力分布图
const message1 = ref<string>("作业难度热力分布表");
const chartRef2 = ref<HTMLElement | null>(null);
const initChart2 = async () => {
  try {
    if (chartRef2.value !== null) {
      const response = await http.get("/api/assignments/difficulty", {
        params: {
          class_id: class_id.value,
          program_id: program_id.value,
        },
      });
      const work_list = response.data.results || [];
      // 1. 空数据情况处理
      if (work_list.length === 0) {
        renderEmptyChart();
        return;
      }

      // 1. 数据转换
      const classes = Array.from(
        new Set(work_list.map((i: any) => i.class_name))
      ).sort(); // X轴：排序后的班级
      const difficulties = ["困难", "中等", "简单"]; // Y轴：固定难度顺序

      // 2. 生成热力图数据格式
      const data = work_list.map((item: any) => {
        return [
          classes.indexOf(item.class_name), // X轴索引
          difficulties.indexOf(item.difficulty), // Y轴索引
          item.count || 0, // 值
        ];
      });

      // 3. ECharts配置
      const option = {
        tooltip: {
          position: "top",
          formatter: (params: any) => {
            return `${classes[params.value[0]]}<br/>
                   难度：${difficulties[params.value[1]]}<br/>
                   数量：${params.value[2]}`;
          },
        },
        grid: {
          height: "65%",
          top: "15%",
        },
        xAxis: {
          type: "category",
          data: classes,
          splitArea: { show: true },
          //   axisLabel: { rotate: 45 },
        },
        yAxis: {
          type: "category",
          data: difficulties,
          splitArea: { show: true },
        },
        visualMap: {
          min: 0,
          max: Math.max(...work_list.map((i: any) => i.count)), // 动态最大值
          calculable: true,
          orient: "horizontal",
          left: "center",
          bottom: "0%",
          inRange: { color: ["#f0f9e7", "#7cccec", "#43a2ca", "#0868ac"] }, // 蓝色系渐变
        },
        series: [
          {
            name: "作业难度分布",
            type: "heatmap",
            data: data,
            label: {
              show: true,
              formatter: (params: any) => params.value[2],
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };

      // 4. 渲染图表
      const chart = echarts.init(chartRef2.value);
      chart.setOption(option);

      // 5. 响应式
      window.addEventListener("resize", () => chart.resize());
    }
  } catch (error) {
    console.error("图表初始化失败:", error);
  }
};

// 表格区域操作
// 定义数据类型
interface TableItem {
  studentName: string;
  studentId: string;
  className: string;
  classes_id: number;
  programName: string;
  programs_id: number;
  totalAssignments: number;
  completed: number;
  late: number;
  notCompleted: number;
  completionRate: number; // 小数形式 0.85 表示 85%
}
// 表格状态
const tableData = ref<TableItem[]>([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 5,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ["5", "10", "20"],
  showTotal: (total: number) => `共 ${total} 条`, // 显示总条数
});

// 列定义
const columns: TableProps["columns"] = [
  {
    title: "学生姓名",
    dataIndex: "studentName",
    fixed: "left",
    width: 120,
  },
  {
    title: "学号",
    dataIndex: "studentId",
    width: 150,
  },
  {
    title: "专业",
    dataIndex: "programName",
    // filters: [
    //   // 需要从接口获取可选项，这里先留空
    // ],
    // filteredValue: filters.value.programs_id ? [filters.value.programs_id] : undefined
    width: 150,
  },
  {
    title: "班级",
    dataIndex: "className",
    // filters: [
    //   // 需要从接口获取可选项，这里先留空
    // ],
    // filteredValue: filters.value.classes_id ? [filters.value.classes_id] : undefined
    width: 150,
  },
  {
    title: "总作业数",
    dataIndex: "totalAssignments",
    width: 110,
  },
  {
    title: "已完成",
    dataIndex: "completed",
    width: 100,
  },
  {
    title: "迟交",
    dataIndex: "late",
    width: 100,
  },
  {
    title: "未完成",
    dataIndex: "notCompleted",
    width: 110,
  },
  {
    title: "完成率",
    dataIndex: "completionRate",
    // customRender: ({ text }: { text: number }) =>
    //   `${(text * 100).toFixed(1)}%`,
    // sorter: true,
    width: 120,
  },
];

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;
    const response = await http.get("/api/assignments/table", {
      params: {
        name: student_name.value,
        classes_id: class_id.value,
        programs_id: program_id.value,
        page: pagination.value.current,
        page_size: pagination.value.pageSize,
      },
    });
    console.log(response);
    tableData.value = response.data.results.list;
    pagination.value.total = response.data.results.totalCount;
  } catch (error) {
    console.error("数据加载失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理表格变化
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  // 更新分页
  pagination.value = { ...pagination.value, ...pag };

  // 更新筛选（需要根据实际接口字段调整）
  filters.value = {
    name: filters.studentName?.[0],
    classes_id: filters.className?.[0],
    programs_id: filters.programName?.[0],
  };

  // 排序处理（需要根据后端支持情况实现）
  if (sorter.field) {
    console.log("排序字段:", sorter.field, "方向:", sorter.order);
  }

  fetchData();
};

onMounted(() => {
  initChart1();
  initChart2();
  fetchData();
});
</script>

<style scoped>
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
.chart {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
}
</style>